package com.uliky.shouyiLibrary.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uliky.common.utils.RandomUtil;
import com.uliky.shouyiLibrary.member.dao.MemberLevelDao;
import com.uliky.shouyiLibrary.member.entity.MemberLevelEntity;
import com.uliky.shouyiLibrary.member.exception.PhoneExistException;
import com.uliky.shouyiLibrary.member.exception.UsernameExistException;
import com.uliky.shouyiLibrary.member.utils.HttpUtils;
import com.uliky.shouyiLibrary.member.vo.MemberLoginVo;
import com.uliky.shouyiLibrary.member.vo.MemberRegistVo;
import com.uliky.shouyiLibrary.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uliky.common.utils.PageUtils;
import com.uliky.common.utils.Query;

import com.uliky.shouyiLibrary.member.dao.MemberDao;
import com.uliky.shouyiLibrary.member.entity.MemberEntity;
import com.uliky.shouyiLibrary.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 注册
     * @param vo
     */
    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        //初始化数据
        //默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //检查手机号和用户名的唯一性
        //为了让controller能够感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        memberEntity.setUsername(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        //需要对密码进行加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encodePassword = bCryptPasswordEncoder.encode(vo.getPassword()); //加密
        memberEntity.setPassword(encodePassword);
        //其他默认信息
        memberEntity.setNickname("首上");
        //保存用户信息
        memberDao.insert(memberEntity);

    }
    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginacct = vo.getLoginacct();
        String password = vo.getPassword();

        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct)
                .or().eq("mobile", loginacct));
        if(memberEntity == null) {
            return null ;
        }else {
            //校验
            String entityPassword = memberEntity.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, entityPassword);
            if (matches) {
                //成功
                return memberEntity;
            } else {
                //失败
                return null ;
            }
        }
    }
    /**
     *  社交登录
     * @return
     */
    @Override
    public MemberEntity oauthLogin(SocialUser socialUser) throws Exception {
        //1.先调用gitee的api查询自己的uid
        String name = "";
        Map<String,String> map=new HashMap<>();
        map.put("access_token", socialUser.getAccess_token());
        HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<String, String>(), map);
        if(response.getStatusLine().getStatusCode()==200){
            String s = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(s);
            int id = (int)jsonObject.get("id");
            name = (String)jsonObject.get("name");
            socialUser.setUid(id+"");
        }
        //2.根据自己的uid查询数据库  判断是否已经存在
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        if(memberEntity !=null) {
            //存在 -- 登录
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in()+"");
            memberDao.updateById(update);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in()+"");
            return  memberEntity;
        }else {
            //不存在 -- 注册
            MemberEntity regist = new MemberEntity();
            regist.setUsername(name);
            regist.setNickname(name);
            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in()+"");
            memberDao.insert(regist);
            return regist;
        }

    }

    @Override
    public void checkPhoneUnique(String phone)  throws PhoneExistException{
        MemberDao memberDao = this.baseMapper;
        Integer i = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if(i>0) {
            throw new PhoneExistException();
        }
    }
    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException{
        MemberDao memberDao = this.baseMapper;
        Integer i = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if(i>0) {
            throw new UsernameExistException();
        }
    }



}